package com.ncs.cns.business.util;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.util.EntityUtils;

import android.os.Environment;

public class UploadUtil{
	private final String TAG = "uploadFile";
    private final String CHARSET = "utf-8"; //设置编码
    private HttpClient client;
    public UploadUtil(HttpClient client) {
    	this.client = client;
	}
    
    public String uploadFile(String url,String dataStr,List<String> filePaths)
    {
    	HttpPost post = new HttpPost(url);
    	MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    	builder.setCharset(Charset.forName("UTF-8"));
    	builder.addTextBody("dataStr",dataStr,ContentType.create("text/plain",CHARSET));
    	for(int i =0;i<filePaths.size();i++){
//    		Bitmap bm = CompressionImageUtil.compressionImg(filePaths.get(i), null, null);    		
//	        InputStream is = new ByteArrayInputStream(CompressionImageUtil.compressionImgSize(bm));
    		builder.addBinaryBody("file"+i+1,new File(CompressionImageUtil.getSmallImgPath(filePaths.get(i))));
    		//InputStream is = CompressionImageUtil.compressImg(filePaths.get(i));
	      //  builder.addBinaryBody("img"+i, is);
    	}
    	post.setEntity(builder.build());
    	String result = "";
    	try {
			HttpResponse response = client.execute(post);
			if(response.getStatusLine().getStatusCode() == 200){
				result = EntityUtils.toString(response.getEntity());
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    	deleteTempUploadImg();
    	return result;
    }
	
    private void deleteTempUploadImg(){
    	File filePath = new File(Environment.getExternalStorageDirectory()
				.getAbsolutePath() + File.separator + "CNSUploadImg" +File.separator);
		if(filePath.isDirectory()){
			File[] f = filePath.listFiles();
			for(int i = 0;i < f.length;i++){
				f[i].delete();
			}			
		}
		filePath.delete();
    }
	
}

